<template>
<!--
  重点:
    1. 如何监听数据的改变,并有所动作( 利用 watch 钩子函数 )
    2. 利用 lodash 插件的 debounce 方法,优化函数防抖
      |-1. 参考文档 https://www.lodashjs.com/docs/lodash.debounce#_debouncefunc-wait0-options
    3. 对搜索结果样式进行匹配高亮处理
    4. 跨组件传参 suggestion(子传父) -> index((父处理)父传子) -> result(子接收)
-->
  <div class="search-suggestion">
    <van-cell v-for="(item, index) in suggestions" :key="index" icon="search" @click="$emit('search',item)">
      <div slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce } from 'lodash'

// 怎么把js学好:(1)复习js基础和js高级 (2):手写promise(a)掘金找手写promise系列(b)b站搜手写promise
// 手写 debounce
// function debounce (fn, wait) {
//   let timer = null
//   return function (val) {
//     console.log(this)
//     const that = this
//     if (timer) {
//       clearTimeout(timer)
//     }
//     timer = setTimeout(() => {
//       fn.call(that, val)
//     }, wait)
//   }
// }
export default {
  name: 'SearchSuggestion',
  components: {

  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: []
      // timer: null,
      // htmlStr: '你好<span style="color: red;">123</span>OVO'
    }
  },
  // 监视者(被监视的数据发生变化时会立即调用 handler 函数)
  // handler 函数为固定写法
  watch: {
    searchText: {
      handler: debounce(async function (val, oldVal) {
        const { data: { data: { options } } } = await getSearchSuggestions({ q: val })
        this.suggestions = options
      }, 500),
      immediate: true
    }
    // 方式1.回顾防抖原理
    // searchText: {
    //   handler (val) {
    //     if (this.timer) {
    //       clearTimeout(this.timer)
    //     }
    //     this.timer = setTimeout(async () => {
    //       const { data: { data: { options } } } = await getSearchSuggestions({ q: val })
    //       this.suggestions = options
    //     }, 500)
    //   },
    //   immediate: true
    // }
  },
  created () {

  },
  methods: {
    highlight (item) {
      console.log(item)
      const reg = new RegExp(this.searchText, 'ig')
      return item.replace(reg, '<span class="active">' + this.searchText + '</span>')
    }
  }
}
</script>

<style lang="less" scoped>
  /deep/ span.active {
    color: #3296fa;
  }
</style>
